from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.db import transaction
from asset.models import DeviceInfo
from mongolog.models import AppsLog


class Command(BaseCommand):
    help = 'Subscribe real-time user activities from redis message queue'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        queryset = AppsLog.objects.mongo_aggregate([
            {
                '$match': {
                    'device_info.device_uuid': {
                        '$exists': True,
                        '$ne': ''
                    },
                    'device_info.userName': {
                        '$exists': True,
                        '$ne': ''
                    },
                    'device_info.device_model': {
                        '$exists': True,
                        '$ne': ''
                    },
                    'device_info.system_version': {
                        '$exists': True,
                        '$ne': ''
                    },
                    'device_info.is_root': {
                        '$exists': True,
                        '$in': ['0', '1']
                    },
                }
            },
            {
                '$project': {
                    'device_info': 1,
                    'log_time': 1,
                    'app': {'$size': '$apps'},
                    'danger_app': {'$size': '$apps_danger'},
                    'risk_app': {'$size': '$apps_risk'},
                    'sensitive_app': {'$size': '$apps_sensitive'}
                }
            },
            {
                '$sort': {'device_info.device_uuid': 1, 'log_time': -1}
            },
            {
                '$group': {
                    '_id': {
                        'device_uuid': '$device_info.device_uuid',
                    },
                    'doc': {'$push': '$$ROOT'}
                }
            },
            {
                '$project': {
                    'doc': {'$arrayElemAt': ['$doc', 0]}
                }
            },
            {
                '$project': {
                    '_id': 0,
                    'device_uuid': '$_id.device_uuid',
                    'object_id': '$doc._id',
                    'mac_addr': '$doc.device_info.mac_address',
                    'user_id': '$doc.device_info.userName',  # Django的外键字段，实际上是username
                    'model': '$doc.device_info.device_model',
                    'os_version': '$doc.device_info.system_version',
                    'app': '$doc.app',
                    'danger_app': '$doc.danger_app',
                    'risk_app': '$doc.risk_app',
                    'sensitive_app': '$doc.sensitive_app',
                    'is_root': '$doc.device_info.is_root',
                }
            }
        ])
        print(queryset)
        device_list = [DeviceInfo(**agg) for agg in queryset]
        print(device_list)
        with transaction.atomic():
            DeviceInfo.objects.all().delete()
            for device in device_list:
                try:
                    device.is_secure = not device.danger_app
                    device.full_clean()
                    device.save()
                except ValidationError:
                    pass
